package com.qf.controller;

import com.github.pagehelper.PageInfo;
import com.qf.bean.*;
import com.qf.enums.CustomerEnum;
import com.qf.bargainexception.PoorException;
import com.qf.service.*;
import com.qf.util.BargainExcelUtil;
import com.qf.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.util.StringUtils;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;
import javax.validation.constraints.NotNull;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import static com.qf.constant.BargainConstant.*;


@Controller
@RequestMapping("/bargain")
@Slf4j
public class BargainController {

    @Autowired   //合同管理
    private BargainService bargainService;

    @Autowired   //审核状态
    private CheckstatusService checkstatusService;

    @Autowired   //合同类型
    private StyleService styleService;

    @Autowired   //付款方式
    private PaystyleService paystyleService;

    @Autowired   //产品类别
    private ProductService productService;

    @Autowired   //合同属性
    private PropertyService propertyService;

    @Autowired   //到期提醒
    private RemindService remindService;

    @Autowired   //资源范围
    private ScopeService scopeService;

    @Autowired  //服务方式
    private ServiceService serviceService;



    @RequestMapping("/findAll")
    public String findAll(@RequestParam(defaultValue = "1")Integer page,
                          String charityname, @RequestParam(defaultValue = "-1") Integer checkstatus,
                          @RequestParam(defaultValue = "-1") Integer styleid,Model model){
        PageInfo<Bargaininfo> pageInfo=bargainService.findAll(page,SIZE,charityname,checkstatus,styleid);
        List<Checkstatus> checkList= checkstatusService.findAllCheck();
        List<Style> styleList=styleService.findAllStyle();
        model.addAttribute("pageInfo",pageInfo);
        model.addAttribute("charityname",charityname);
        model.addAttribute("checkList",checkList);
        model.addAttribute("styleList",styleList);
        model.addAttribute("checkstatus",checkstatus);
        model.addAttribute("styleid",styleid);

        return "bargain/bargain-list";
    }

    //一个合同的信息
    @RequestMapping("/info")
    public String info(Integer id, Model model){
        Bargaininfo bargain=bargainService.findOne(id);
        model.addAttribute("bargain",bargain);
        return "bargain/bargain-info";
    }

    //跳转到添加页面，同时查询出其他需要的数据
    @RequestMapping("/add-ui")
    public String addUI(Model model){

        List<Checkstatus> checkList= checkstatusService.findAllCheck();
        List<Style> styleList=styleService.findAllStyle();
        List<Paystyle> payList=paystyleService.findAllPaystyle();
        List<Product> productList=productService.findAllProduct();
        List<Property> proList=propertyService.findAllProperty();
        List<Remind> remindList=remindService.findAllRemind();
        List<Scope> scopeList=scopeService.findAllScope();
        List<Service> serviceList=serviceService.findAllService();

        model.addAttribute("checkList",checkList);
        model.addAttribute("styleList",styleList);
        model.addAttribute("payList",payList);
        model.addAttribute("productList",productList);
        model.addAttribute("proList",proList);
        model.addAttribute("remindList",remindList);
        model.addAttribute("scopeList",scopeList);
        model.addAttribute("serviceList",serviceList);
        return "bargain/bargain-add";
    }

    //添加时异步校验合同名称
    @PostMapping("/checkBargainName")
    @ResponseBody
    public ResultVO checkBargainName(String bargainname){
        if (StringUtils.isEmpty(bargainname)){
            return new ResultVO(21,"合同名称为空",null);
        }
        Integer count=bargainService.findCountByName(bargainname);
        if (count>0){
            return new ResultVO(22,"合同名称已被占用",null);
        }else{
            return new ResultVO(0,"合同名称可用",null);
        }
    }

    //添加合同信息
    @PostMapping("/addBargain")
    @ResponseBody
    public ResultVO addBargain(@Valid Bargaininfo bargaininfo, BindingResult bindingResult){

        if (bargaininfo.getPropertyid()<0){
            return new ResultVO(31,"请选择合同性质",null);
        }
        if (bargaininfo.getStyleid()<0){
            return new ResultVO(32,"请选择合同类型",null);
        }
        if (bargaininfo.getPaystyle()<0){
            return new ResultVO(33,"请选择付款方式",null);
        }
        if (bargaininfo.getCheckstatus()<0){
            return new ResultVO(34,"请选择审核状态",null);
        }
        //将BigDecimal类型数据转化成int类型，并判断是否大于0
        int count = bargaininfo.getCount().intValue();
        if (count<0){
            return new ResultVO(35,"合同总金额不规范",null);
        }

        if (bindingResult.hasErrors()){
            String message = bindingResult.getFieldError().getDefaultMessage();
            throw new PoorException(CustomerEnum.PARAM_ERROR.getCode(),message);
        }

        bargainService.addBargain(bargaininfo);
        return new ResultVO(0,"",null);

    }

    //跳转到修改页面，回显出相应的值
    @RequestMapping("/update-ui")
    public String updateBargain(Integer id,Model model){
        //根据id查询具体的值
        Bargaininfo bargaininfo=bargainService.findOne(id);
        //其他的条件集合
        List<Checkstatus> checkList= checkstatusService.findAllCheck();
        List<Style> styleList=styleService.findAllStyle();
        List<Paystyle> payList=paystyleService.findAllPaystyle();
        List<Product> productList=productService.findAllProduct();
        List<Property> proList=propertyService.findAllProperty();
        List<Remind> remindList=remindService.findAllRemind();
        List<Scope> scopeList=scopeService.findAllScope();
        List<Service> serviceList=serviceService.findAllService();

        model.addAttribute("bargaininfo",bargaininfo);
        model.addAttribute("checkList",checkList);
        model.addAttribute("styleList",styleList);
        model.addAttribute("payList",payList);
        model.addAttribute("productList",productList);
        model.addAttribute("proList",proList);
        model.addAttribute("remindList",remindList);
        model.addAttribute("scopeList",scopeList);
        model.addAttribute("serviceList",serviceList);
        return "bargain/bargain-update";
    }

    //修改合同信息
    @RequestMapping("/updateBargain")
    @ResponseBody
    public ResultVO updateBargain(@Valid Bargaininfo bargaininfo, BindingResult bindingResult){

        //将BigDecimal类型数据转化成int类型，并判断是否大于0
        int count = bargaininfo.getCount().intValue();

        if (count<0){
            return new ResultVO(36,"合同总金额不规范",null);
        }

        if (bindingResult.hasErrors()){
            String message = bindingResult.getFieldError().getDefaultMessage();
            throw new PoorException(CustomerEnum.PARAM_ERROR.getCode(),message);
        }

        //执行修改
        bargainService.updateBargain(bargaininfo);
        return new ResultVO(0,"",null);

    }

    //修改时异步校验合同名称
    @PostMapping("/checkBargainNameById")
    @ResponseBody
    public ResultVO checkBargainNameById(String bargainname,Integer id){
        if (StringUtils.isEmpty(bargainname)){
            return new ResultVO(41,"合同名称为空",null);
        }

        Integer count=bargainService.findCountById(bargainname,id);
        if (count>0){
            return new ResultVO(22,"合同名称已被占用",null);
        }else{
            return new ResultVO(0,"合同名称可用",null);
        }
    }

    //删除单个合同（假删除，修改状态）
    @GetMapping("/deleteById")
    public void deleteById(HttpServletResponse response,Integer id){

        try {
            response.setContentType("text/html;charset=utf-8");
            PrintWriter writer = response.getWriter();

            //根据id查询状态（审核中和已通过不能删除）
            Bargaininfo bargaininfo = bargainService.findOne(id);
            if (bargaininfo.getCheckstatus()==1||bargaininfo.getCheckstatus()==3){
                //能删除  修改状态
                Integer count=bargainService.deleteById(id, DELETE);
                if (count==1){
                    writer.print("<script>alert('删除成功');location.href='/bargain/findAll'</script>");
                }else {
                    writer.print("<script>alert('删除失败');location.href='/bargain/findAll'</script>");
                }
            }else{
                //不能删除
                writer.print("<script>alert('请先修改审核状态');location.href='/bargain/findAll'</script>");
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    //批量删除和导出
    @PostMapping("/deleteOrOut")
    public void deleteOrOut(Integer[] bargainid,HttpServletResponse response,String method){

        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = null;
        try {
            writer = response.getWriter();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (bargainid==null||bargainid.length==0){
            writer.print("<script>alert('请选择要操作的合同');location.href='/bargain/findAll'</script>");
        }else{
            if (method.equals("delete")) {
                List<Integer> bargainidList=new ArrayList<>();
                for (Integer id : bargainid) {
                    //根据id查询salinfo
                    Bargaininfo bargaininfo = bargainService.findOneById(id);
                    if (bargaininfo.getCheckstatus()==1 || bargaininfo.getCheckstatus()==3){
                        bargainidList.add(id);
                    }
                }
                if (bargainidList==null || bargainidList.size()==0){
                    writer.print("<script>alert('请选择可以删除的合同');location.href='/bargain/findAll'</script>");
                }else{
                    Integer count = bargainService.deleteInIds(bargainidList);
                    if (count > 0) {
                        writer.print("<script>alert('删除成功');location.href='/bargain/findAll'</script>");
                    } else {
                        writer.print("<script>alert('删除失败');location.href='/bargain/findAll'</script>");
                    }
                }
            }else if (method.equals("out")){
                try {
                    //导出数据
                    //1.查询集合
                    List<Bargaininfo> bargainList=bargainService.findBargainByIds(bargainid);
                    //2.导出
                    BargainExcelUtil.createFirst("合同信息");
                    BargainExcelUtil.createOthers(bargainList);
                    SimpleDateFormat format=new SimpleDateFormat("yyyyMMddhhmmss");
                    BargainExcelUtil.export(new FileOutputStream("f://"+(format.format(new Date()))+".xls"));
                    writer.print("<script>alert('导出成功,请在F盘查看');location.href='/bargain/findAll'</script>");
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }


    }

}
